package com.srwl.mytx.contrack;


import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.greendao.ContactDao;
import com.srwl.mytx.domain.Contact;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.im.IMSClientBootstrap;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.widget.ConfirmDialog;
import com.starrtc.starrtcsdk.api.XHClient;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by dahai2070 on 2018/2/22 0022.
 */
public class UpdateUserInfoPresenterImpl implements RegisterContrack.Presenter {
    private static final String TAG = "UpdataUserInfoPresenter";
    private RegisterContrack.View view;
    private Context context;
    private int count = 120;

    public UpdateUserInfoPresenterImpl(@NonNull RegisterContrack.View view, @NonNull Context context) {
        this.view = view;
        // view.setPresenter(this);
        this.context = context;
    }

    @Override
    public void start() {

    }

    @Override
    public void register(final User user, String mobileCode) {

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("mobileCode", mobileCode);
        map.put("userInfo", user);
        view.setRegisterButtonStatus(false);
        view.showProgressDialog("正在绑定");
        RetrofitManager
                .getInstance()
                .createRequest(UserService.class)
                .userBindAccount(map)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        view.disMissProgressDialog();
                        //按键恢复
                        view.setRegisterButtonStatus(true);
                        CommonResult commonResult = response.body();
                        if (!response.isSuccessful() || commonResult == null) {
                            Log.d(TAG, response.code() + response.message());
                            view.showToast(context.getString(R.string.system_busy));
                            return;
                        }
                        //绑定出错
                        if (commonResult.isError()) {
                            Log.e(TAG, commonResult.getStatus() + commonResult.getMsg());
                            switch (commonResult.getStatus()) {
                                case Constant.MOBILE_CODE_ERROR:
                                    view.showToast(context.getString(R.string.mobile_code_error));
                                    view.showRegisterFail();
                                    break;
                                case Constant.MOBILE_CODE_EXPIRE:
                                    view.showToast(context.getString(R.string.mobile_code_expire));
                                    view.showRegisterFail();
                                    break;
                                case Constant.MOBILE_CODE_USED:
                                    view.showToast(context.getString(R.string.mobile_code_used));
                                    view.showRegisterFail();
                                    break;
                                case Constant.SEND_MOBILE_CODE_FAIL_ENGAGED:
                                    ConfirmDialog dialog = new ConfirmDialog(context, "提示", context.getString(R.string.phone_number_engaged));
                                    dialog.show();
                                    view.showSendMobileCodeFail();
                                    view.showRetrievePassWord();
                                    break;
                                default:
                                    view.showToast(context.getString(R.string.system_busy));
                            }
                            return;
                        }

                        // TODO: 2019/5/10 后端返回手机号添加到...
                        //清除用户的信息
                        IMSClientBootstrap.getInstance().logout();
                        XHClient.getInstance().getLoginManager().logout();
                        JSONObject o = (JSONObject) commonResult.getData();
                        User loginUser = o.getObject("userInfo", User.class);
                        Log.i(TAG, "userInfo: " + loginUser);
                        if (o.containsKey("token")) {
                            Helper.getInstance().removeLoginUserInfo();
                            DBManager.getInstance().closeDB();
                            String token = o.getString("token");
                            Log.d(TAG, "1111  token:" + token);
                            UserProfileManager.getInstance().setUserToken(token);
                            List<Contact> contacts = JSONObject.parseArray(o.getString("contacts"), Contact.class);
                            //判断服务器端是否有联系人信息
                            if (contacts != null && contacts.size() != 0) {
                                //如果有联系人信息,则更新联系人信息
                                ContactDao contactDao = DBManager.getInstance().getDaoSession().getContactDao();
                                contactDao.deleteAll();//保存之前，清空所有联系人，这样保证数据与服务端同步
                                List<User> users = new ArrayList<>();
                                // List<InfiniteConnect>infiniteConnects=new ArrayList<>();
                                for (Contact contact : contacts) {
                                    contact.settId(contact.getUser().getuId());
                                    users.add(contact.getUser());
//                                for (InfiniteConnect infiniteConnect : contact.getInfinite()) {
//                                    infiniteConnect.setcId(contact.getcId());
//                                }
//                                infiniteConnects.addAll(contact.getInfinite());
                                }
                                contactDao.insertOrReplaceInTx(contacts);
                                DBManager.getInstance().getDaoSession().getUserDao().insertOrReplaceInTx(users);
                                Helper.getInstance().refreshCache();
                                LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(context);
                                localBroadcastManager.sendBroadcast(new Intent(Constant.ACTION_CONTACT_CHANGED));
                                //这种情况，后端做了账户合并操作，前端需要登出阿里im ,根据当前用户id  重新登录
                            }

                        }
                        UserProfileManager.getInstance().syncLoginUserInfo(loginUser);
                        //登录到声网
                       // String loginUserId = UserProfileManager.getInstance().getLoginUserInfo().getuId();
                        //MyApplication.getInstance().getmAgoraAPI().logout();
                       // MyApplication.getInstance().getmAgoraAPI().login2("f7f80a83085943c8bd1d7fc5e87a0a91", loginUser.getuId(), "_no_need_token", 0, "", 30, 3);
                        IMSClientBootstrap.getInstance().login();
                        Helper.getInstance().initStarRtc(loginUser.getuId());
                        Helper.getInstance().starRtcLogin();
                        view.showToast("绑定成功");
                        view.showRegisterSuccess();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        view.disMissProgressDialog();
                        //按键恢复
                        view.setRegisterButtonStatus(true);
                    }
                });
    }

    @Override
    public void pickAvatar() {

    }


    /**
     * 上传头像到服务端，因为注册activity 要销毁，
     * 所以该线程不能和注册activity互相持有变量
     * 绑定不需要更新头像
     */
    @Override
    public void uploadAvatar() {

    }

    @Override
    public void sendMobileCode(String phoneNumber) {
        if (!Helper.getInstance().isNetworkConnected()){
            Toast.makeText(context, context.getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
        view.setSendMobileCodeButtonStatus(false);
        view.showProgressDialog(context.getString(R.string.mobile_code_sending));
        RetrofitManager
                .getInstance()
                .createRequest(UserService.class)
                .sendBindingMobileCode(phoneNumber)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        view.disMissProgressDialog();
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            view.setSendMobileCodeButtonStatus(true);
                            view.showToast(context.getString(R.string.system_busy));
                            view.setSendMobileCodeButtonText(context.getString(R.string.re_send_mobile_code));
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }
                        // 如果短信发送成功
                        if (result.isOK()) {
                            view.showToast(context.getString(R.string.SMScode_sended));
                            //短信验证码按键倒计时
                            startCount();
                            return;
                        }
                        //如果短信没发送成功，重置按键为可用状态
                        view.setSendMobileCodeButtonStatus(true);
                        view.setSendMobileCodeButtonText(context.getString(R.string.re_send_mobile_code));
                        Log.e(TAG, "onResponse: " + result.getMsg());
                        switch (result.getStatus()) {
                            case Constant.SEND_MOBILE_CODE_FAIL_HAVE_NO_COUNT:
                                // view.showToast(String.format(context.getString(R.string.send_mobile_code_remain_time), result.getData().toString()));
                                ConfirmDialog dialog1 = new ConfirmDialog(context, "提示", String.format(context.getString(R.string.send_mobile_code_remain_time), result.getData().toString()));
                                dialog1.show();
                                view.showSendMobileCodeFail();
                                return;
                            case Constant.SEND_MOBILE_CODE_FAIL_ENGAGED:
                                //view.showToast(context.getString(R.string.phone_number_engaged));
                                ConfirmDialog dialog = new ConfirmDialog(context, "提示", context.getString(R.string.phone_number_engaged));
                                dialog.show();
                                view.showSendMobileCodeFail();
                                view.showRetrievePassWord();
                                return;
                            case Constant.PHONE_NUMBER_FORMAT_ERROR:
                                view.showToast("手机号格式错误");
                                view.showSendMobileCodeFail();
                                return;
                            default:
                                view.showToast(context.getString(R.string.system_busy));

                        }

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        view.disMissProgressDialog();
                        view.setSendMobileCodeButtonText(context.getString(R.string.re_send_mobile_code));
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        view.showToast(context.getString(R.string.system_busy));
                        view.setSendMobileCodeButtonStatus(true);
                    }
                });
    }


    public void startCount() {
        count = 120;
        final Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {

                if (count > 0) {
                    view.setSendMobileCodeButtonText(count + "");
                    count--;
                } else {
                    timer.cancel();
                    view.setSendMobileCodeButtonText(context.getString(R.string.re_send_mobile_code));
                    view.setSendMobileCodeButtonStatus(true);

                }
            }
        };
        timer.schedule(task, 0, 1000);
    }
}
